package ModelLayer; //makes this class a part of the ModelLayer package

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Write a description of class ItemContainer here.
 * 
 * @author (ucn-1semprojekt-dm78-gruppe1)
 * 
 */
public class ItemContainer
{
	private ArrayList<SaleItem> saleitems;
	private ArrayList<RentItem> rentitems;
	private static ItemContainer instance;

	/**
	 * Constructor for objects of class ItemContainer
	 */
	private ItemContainer()
	{
		saleitems = new ArrayList<SaleItem>();
		rentitems = new ArrayList<RentItem>();
	}

	// Singleton
	public static ItemContainer getInstance()
	{
		if (instance == null)
		{
			instance = new ItemContainer();
		}
		return instance;
	}

	public void addSaleItem(SaleItem saleitem)
	{
		saleitems.add(saleitem);
	}

	public void addRentItem(RentItem rentitem)
	{
		rentitems.add(rentitem);
	}

	public void saveToFile() throws IOException
	{
		FileHandler.gem(saleitems,"SaleItem.db");
		FileHandler.gem(rentitems,"RentItem.db");
	}

	@SuppressWarnings("unchecked")
	public void loadFromFile() throws IOException,ClassNotFoundException
	{
		try
		{
			saleitems = (ArrayList<SaleItem>)FileHandler.hent("SaleItem.db");
			rentitems = (ArrayList<RentItem>)FileHandler.hent("RentItem.db");
		}
		catch (Exception ex)
		{
			// throw new IOException("Ikke muligt at lave et gyldigt filnavn til");
		}
	}

	public SaleItem getSaleItem(int itemnr)
	{
		int index = 0;
		int index2 = 0;
		boolean found = false;
		while (!found && index < saleitems.size())
		{
			SaleItem saleitem = saleitems.get(index);
			if (saleitem.getItemnr() == itemnr)
			{
				found = true;
				index2 = index;
			}
			index++;
		}
		if (found == true)
		{
			return saleitems.get(index2);
		}
		else
		{
			return null;
		}
	}

	public RentItem getRentItem(int itemnr)
	{
		int index = 0;
		int index2 = 0;
		boolean found = false;

		while (!found && index < rentitems.size())
		{
			RentItem rentitem = rentitems.get(index);
			if (rentitem.getItemnr() == itemnr)
			{
				found = true;
				index2 = index;
			}
			index++;
		}
		if (found == true)
		{
			return rentitems.get(index2);
		}
		else
		{
			return null;
		}
	}

	public List<SaleItem> getSaleItemList()
	{
		return this.saleitems;
	}
}